package edu.nf.postlikework.common.confirm;

import com.fasterxml.jackson.databind.ObjectMapper;
import edu.nf.postlikework.common.config.RabbitConfig;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 *
 * @author zjl
 * @date 2025/10/15
 * 封装
 */
@Component
@RequiredArgsConstructor
public class RabbitManager<T> {
    private final RabbitTemplate rabbitTemplate;

    public void send(String exchange,String routingKey,
                     String callbackBeanName,T data){
        try{
            //创建cdata对象并设置一个id
            CorrelationData cdata = new CorrelationData(UUID.randomUUID().toString());
            //将投递的数据转换为byte[]
            byte[] bytes = new ObjectMapper().writeValueAsBytes(data);
            //将byte封装为Message对象
            Message message = new Message(bytes);
            //创建一个投递失败时返回的消息对象
            ReturnedMessage returnedMessage = new ReturnedMessage(message,0
                    ,callbackBeanName,exchange,routingKey);
            cdata.setReturned(returnedMessage);
            rabbitTemplate.convertAndSend(exchange, routingKey,data,cdata);
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
}
